package org.luxor.storage.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.luxor.commons.core.annotation.SysLog;
import org.luxor.commons.core.validator.group.AddGroup;
import org.luxor.commons.core.validator.group.UpdateGroup;
import org.luxor.commons.core.web.controller.BaseRestController;
import org.luxor.commons.core.web.data.R;
import org.luxor.commons.jdbc.metadata.PageQuery;
import org.luxor.commons.storage.constant.StorageType;
import org.luxor.storage.entity.OssFileEntity;
import org.luxor.storage.service.IOssFileMgrService;
import org.luxor.storage.utils.ParamExtUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.MimeTypeUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

/**
 * OSS文件管理
 *
 * @author Mr.yan @date 2020/3/11
 */
@RestController
@RequestMapping(value = "/sys/storage/file")
@Api(tags = "OSS文件管理")
public class FileManageController extends BaseRestController {

    @Resource
    private IOssFileMgrService ossFileMgrService;

    @GetMapping("/download")
    @PreAuthorize("hasPermission(#request,'sys:storage:file:download')")
    @ApiOperation("OSS文件下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileFullPath", value = "文件存储路径(fileFullPath)", paramType = "query", required = true
                    , example = "/images/2020-03-23/background_0_000939920.jpg"),
            @ApiImplicitParam(name = "storageType", value = "存储类型(0：本地磁盘 1：Minio 2：FastDfs 3：七牛  4：阿里云  5：腾讯云)"
                    , example = "1", paramType = "query", dataType = "Integer", required = true)
    })
    public void download(@RequestParam Integer storageType, @RequestParam String fileFullPath, HttpServletResponse response) {
        String fileFullName = ParamExtUtils.extFileFullName(fileFullPath);
        String mimeType = ParamExtUtils.getMimeType(fileFullName);
        response.addHeader("Content-Type", mimeType);
        if (MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE.equals(mimeType)) {
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileFullName + "\"");
        }
        ossFileMgrService.download(StorageType.valueOf(storageType), fileFullPath, response);
    }

    /**
     * OSS文件对象列表
     */
    @PostMapping("/list")
    @PreAuthorize("hasPermission(#request,'sys:storage:file:list')")
    @ApiOperation("OSS文件对象列表")
    public R<IPage<OssFileEntity>> list(@RequestBody PageQuery<HashMap> searchPage) {
        IPage<OssFileEntity> data = ossFileMgrService.page(searchPage.getPage(), searchPage.getSearch());
        return R.ok(data);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasPermission(#request,'sys:storage:file:info')")
    @ApiOperation("获取OSS文件对象信息")
    @ApiImplicitParam(name = "id", value = "OSS文件对象ID", paramType = "path", required = true)
    public R<OssFileEntity> info(@PathVariable("id") Long id) {
        OssFileEntity ossFile = ossFileMgrService.getById(id);
        return R.ok(ossFile);
    }

    /**
     * 保存
     */
    @SysLog("保存OSS文件对象")
    @PostMapping("/save")
    @PreAuthorize("hasPermission(#request,'sys:storage:file:save')")
    @ApiOperation("保存OSS文件对象")
    public R<OssFileEntity> save(@Validated(AddGroup.class) @RequestBody OssFileEntity ossFile) {
        ossFile.setUpdateTime(new Date());
        ossFileMgrService.save(ossFile);
        return R.ok(ossFile);
    }

    /**
     * 修改
     */
    @SysLog("修改OSS文件对象")
    @PutMapping("/update")
    @PreAuthorize("hasPermission(#request,'sys:storage:file:update')")
    @ApiOperation("修改OSS文件对象")
    public R<OssFileEntity> update(@Validated(UpdateGroup.class) @RequestBody OssFileEntity ossFile) {
        ossFile.setUpdateTime(new Date());
        ossFileMgrService.updateById(ossFile);
        return R.ok(ossFile);
    }

    /**
     * 删除
     */
    @SysLog("删除OSS文件对象")
    @DeleteMapping("/delete")
    @PreAuthorize("hasPermission(#request,'sys:storage:file:delete')")
    @ApiOperation("删除OSS文件对象")
    public R delete(@RequestBody Long[] ids) {
        ossFileMgrService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
